//This program is originally from the book �Operating System //Concepts in Java�,
// (Silberschatz) 7th Edition.
import java.io.*;
import java.util.*;

public class TestProcessBuilder {

	static void createProcess(String command) {
		CommandThread pb = new CommandThread(command);
		new Thread(pb).start();
	}

	public static void main(String[] args) throws java.io.IOException {
		long loginTime = Calendar.getInstance().getTimeInMillis();
		long logoutTime;
		long sessionDuration;
		String commandLine;
		File errorLog = new File("/Applications/Android development/workspace/OPS_Labb_1/res/errorLog.txt");
		if(errorLog.exists()){
			errorLog.delete();
		}
		errorLog.createNewFile();
		BufferedReader console = new BufferedReader(new InputStreamReader(
				System.in));
		System.out.println("\n\n***** Welcome to the Java Command Shell *****");
		System.out
				.println("If you want to exit the shell, type END and press RETURN.\n");
		// we break out with �END�
		while (true) {
			// show the Java shell prompt and read what command they entered
			System.out.print("jsh>");
			commandLine = console.readLine();
			// if user entered a return, just loop again
			if (commandLine.equals("")) {
				continue;
			}
			if (commandLine.equals("showerrlog")) {
				BufferedReader in = new BufferedReader(new FileReader(errorLog));
				String line;
				while((line = in.readLine()) != null){
					System.out.println(line);
				}
				in.close();
			}
			if (commandLine.toLowerCase().equals("end")) { // User wants to end
															// shell
				System.out
						.println("\n***** Command Shell Terminated. See you next time. BYE for now. *****\n");
				logoutTime = Calendar.getInstance().getTimeInMillis();
				sessionDuration = logoutTime - loginTime;
				String loginString = convertMillis(loginTime);
				String logoutString = convertMillis(logoutTime);
				String sessionDurationString = convertMillis(sessionDuration);
				String sessionString = "";
				sessionString += "Login Time " + loginString + "\n";
				sessionString += "Logout Time " + logoutString + "\n";
				sessionString += "Duration " + sessionDurationString + "\n";
				System.out.println(sessionString);
				System.exit(0);
			}
			// Process the command entered by the user, by creating process
			createProcess(commandLine);
		}
	}

	private static String convertMillis(long millis) {
		long remainder = millis % 86400000;
		millis = remainder;
		remainder = millis % 3600000;
		long hours = (millis - remainder) / 3600000;
		millis = remainder;
		remainder = millis % 60000;
		long minutes = (millis - remainder) / 60000;
		millis = remainder;
		remainder = millis % 1000;
		long seconds = (millis - remainder) / 1000;
		String returnString = "";
		returnString += hours + ":" + minutes + ":" + seconds;
		return returnString;
	}
}